package com.lotus.lqmp.service.common.factory;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.parser.NacosDataYamlParser;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Executor;

/**
 * 监听nacos配置
 * @author Liwei.Zhang3
 * @since 2022/01/12 09:17
 */
@Slf4j
@Component
public class RefreshConfigBean implements InitializingBean {

    @Autowired
    private NacosConfigManager nacosConfigManager;

    @Autowired(required = false)
    Map<String, RefreshConfigHandler> refreshConfigHandlerMap;

    @Override
    public void afterPropertiesSet() throws Exception {
        nacosConfigManager.getConfigService().addListener("xxx-server", "DEFAULT_GROUP", new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String config) {
                log.info("监听nacos配置文件内容{}", config);
                try {
                    NacosDataYamlParser yamlParser = new NacosDataYamlParser();
                    Map<String, Object> nacosData = yamlParser.parseNacosData(config, "yml");
                    for (Map.Entry<String, RefreshConfigHandler> entry: refreshConfigHandlerMap.entrySet()) {
                        String key = entry.getKey();
                        Object value = nacosData.get(key);
                        log.info("解析yml配置 {}-{}", key, value);
                        if (value != null) {
                            entry.getValue().handleConfig(value);
                        }
                    }
                } catch (Exception e) {
                    log.error("refresh rateLimitMap error", e);
                }
            }
        });
    }
}
